import model.SearchProductCondition
import model.MonthProductCondition
import util.IdGenerator
import util.DateUtils
import grails.converters.JSON
import java.text.SimpleDateFormat

class ProductController {
    def idGenerator = new IdGenerator()
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    // 倒叙排列 只显示进货的商品
    def list = {
        if(!params.max) params.max = 10
        if(!params.offset) params.offset = 0
        if(!params.sort) params.sort = "id"
        if(!params.order) params.order = "desc"

        def result = Product.createCriteria().list(params) {
                eq("productFlag","进货")
        }
        [productInstanceList:result]
    }

    def listSearch = {
        // 搜索日期不为空的情况
        if (params.searchDate_value ){
            def year = params.searchDate_year
            def month = params.searchDate_month
            def day = params.searchDate_day
            def searchDateStr = year + "-" + month + "-" + day
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd")
            Date searchDate = sdf.parse(searchDateStr)

            def criteria = Product.createCriteria()
            def resultList = criteria.list(params){
                ge("time",searchDate)
                le("time",searchDate+1)
                eq ("productFlag","进货")
            }
            render(view:"list" , model:[productInstanceList:resultList])
        }
        // 搜索日期为空的情况
        else
            redirect(controller:'product',action:'list')
    }

    def show = {
        def productInstance = Product.get( params.id )

        if(!productInstance) {
            flash.message = "Product not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ productInstance : productInstance ] }
    }

    //每批货物中每个产品销售的详细情况
    def productDetailList ={
        //if(!params.max) params.max = 10
        if(!params.sort) params.sort = "id"
        if(!params.order) params.order = "desc"

        ProductDTO dto = new ProductDTO()

        // 计算某批次货物库存
        def remain=null
        def hql1="select p.amount,p.inPrice,p.outPrice,p.modelNo from Product p where p.productFlag='进货' and p.productName="+"'"+params.id+"'";
        def resultList1 = Product.executeQuery(hql1)
        
        def hql2="select sum(p.amount) from Product p where p.productFlag='卖出' and p.productName="+"'"+params.id+"'";
        def resultList2 = Product.executeQuery(hql2)
        if (resultList2!=[null]){
            remain = resultList1[0][0]-resultList2[0]
        }
        else{
            remain = resultList1[0][0]
        }
        dto.setInPrice(resultList1[0][1])
        dto.setOutPrice(resultList1[0][2])
        dto.setModelNo(resultList1[0][3])

        [ productInstanceList: Product.findAllByProductNameAndProductFlag(params.id,"卖出"),remain:remain,dto:dto ]
    }
    
    def delete = {
        def productInstance = Product.get( params.id )
        if(productInstance) {
            productInstance.delete()
            flash.message = "Product ${params.id} deleted"
            redirect(action:list)
        }
        else {
            flash.message = "Product not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def productInstance = Product.get( params.id )

        if(!productInstance) {
            flash.message = "Product not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ productInstance : productInstance ]
        }
    }

    def update = {
        def productInstance = Product.get( params.id )
        if(productInstance) {
            productInstance.properties = params
            if(!productInstance.hasErrors() && productInstance.save()) {
                flash.message = "Product ${params.id} updated"
                redirect(action:show,id:productInstance.id)
            }
            else {
                render(view:'edit',model:[productInstance:productInstance])
            }
        }
        else {
            flash.message = "Product not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def productInstance = new Product()
        productInstance.properties = params
        return ['productInstance':productInstance]
    }

    //产品售出
    def sellDetail ={
        def productInstance = new Product()
        productInstance.properties = params
        return ['productInstance':productInstance]
    }

    // 保存生成产品信息
    def save = {
        def productName = params.productName+idGenerator.getId()
        def productInstance = new Product(params)
        if(!productInstance.hasErrors() && productInstance.save()) {
            productInstance.setProductName(productName)
            flash.message = "Product ${productInstance.id} created"
            redirect(action:show,id:productInstance.id)
        }
        else {
            render(view:'create',model:[productInstance:productInstance])
        }
    }

    // 保存售出产品信息
    def sellSave = {
        def productInstance = new Product(params)
        if(!productInstance.hasErrors() && productInstance.save()) {
            flash.message = "Product ${productInstance.id} created"
            redirect(action:show,id:productInstance.id)
        }
        else {
            render(view:'create',model:[productInstance:productInstance])
        }
    }

    //产品查询的Action
    def search = { SearchProductCondition  searchCondition ->
    	if(request.method == "POST") {
            if(!params.sort) params.sort = "id"
            if(!params.order) params.order = "desc"
            
    		def criteria = Product.createCriteria()

    		def resultList = criteria.list(params){
    			and {
    				if(searchCondition.productName)    					
    					like ('productName',"%${searchCondition.productName}%")	
				    if(searchCondition.modelNo)
    					like ('modelNo',"%${searchCondition.modelNo}%")
                    eq("productFlag","进货")
    			}
    		}
    		render(view:"listProduct" , model:[productList: resultList]);
    	}
    }

    // 导出excel的Action
    def export = {
        response.setHeader("Content-disposition", "attachment; filename=requests.xls")
        response.contentType = "application/vnd.ms-excel"

        //定义header map
        def header = [:]
        //header.id = "Id"
        header.productName = "产品名称"
        header.amount = "数量"
        header.inPrice = "进价"
        header.modelNo = "型号"
        header.outPrice = "零售价"
        header.supplier = "零售商"
        header.catalog = "产品分类"
        header.time = "进货时间"
        header.productFlag = "货品情况"
        
        ExcelUtils.writeExcel(response.outputStream, header, Product.findAllByProductFlag("进货"))
    }

    // 月报表查询的Action
    def monthProductReport = { MonthProductCondition  monthProductCondition ->
        if(request.method == "POST") {
            if(!params.sort) params.sort = "id"
            if(!params.order) params.order = "desc"
            
            def startDate = monthProductCondition.startDate
            def endDate = monthProductCondition.endDate

    		def criteria = Product.createCriteria()

    		def resultList = criteria.list(params){
                ge("time",startDate)
                le("time",endDate)
                eq ("productFlag","卖出")
    		}
    		render(view:"monthProductReportList" , model:[productList: resultList,startDate:startDate,endDate:endDate]);
    	}
    }

    // 将月报表查询结果导出成excel的Action
    def monthProductReportExport = {
        response.setHeader("Content-disposition", "attachment; filename=requests.xls")
        response.contentType = "application/vnd.ms-excel"

        //定义header map
        def header = [:]

        header.productName = "产品名称"
        header.amount = "数量"
        header.inPrice = "进价"
        header.modelNo = "型号"
        header.outPrice = "零售价"
        header.supplier = "零售商"
        header.catalog = "产品分类"
        header.time = "进货时间"
        header.productFlag = "货品情况"

        def startDate=params.startDate
        SimpleDateFormat sdf= new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",Locale.US)
        Date d1 = sdf.parse(startDate)
        
        def endDate = params.endDate
        Date d2 = sdf.parse(endDate)

        def criteria = Product.createCriteria()
        def resultList = criteria.list{
            ge("time",d1)
            le("time",d2)
            eq ("productFlag","卖出")
        }
        ExcelUtils.writeExcel(response.outputStream, header, resultList)
    }

    // 按照月查询报表
    def everyMonthProductReport = {
    }

    def doEveryMonthProductReport = {
        def year = params.pickDate_year
        def month = params.pickDate_month
        def iYear = Integer.parseInt(year)
        def iMonth = Integer.parseInt(month)

        def startDate = DateUtils.getMonthStart(year,month)
        def iDay = DateUtils.getMonthOfDays(iYear,iMonth)

        def c = Calendar.getInstance()
        c.set(iYear,iMonth-1,iDay)
        def endDate = c.getTime()

        def criteria = Product.createCriteria()
        def resultList = criteria.list(params){
            ge("time",startDate)
            le("time",endDate)
            eq ("productFlag","卖出")
        }
        render(view:"everyMonthProductReport" , model:[productInstanceList: resultList,startDate:startDate,endDate:endDate])
    }

    // 将每月的报表查询结果导出成excel的Action
    def everyMonthProductReportExport = {
        response.setHeader("Content-disposition", "attachment; filename=requests.xls")
        response.contentType = "application/vnd.ms-excel"

        //定义header map
        def header = [:]

        header.productName = "产品名称"
        header.amount = "数量"
        header.inPrice = "进价"
        header.modelNo = "型号"
        header.outPrice = "零售价"
        header.supplier = "零售商"
        header.catalog = "产品分类"
        header.time = "进货时间"
        header.productFlag = "货品情况"

        def startDate=params.startDate
        SimpleDateFormat sdf= new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",Locale.US)
        Date d1 = sdf.parse(startDate)

        def endDate = params.endDate
        Date d2 = sdf.parse(endDate)

        def criteria = Product.createCriteria()
        def resultList = criteria.list{
            ge("time",d1)
            le("time",d2)
            eq ("productFlag","卖出")
        }
        ExcelUtils.writeExcel(response.outputStream, header, resultList)
    }

    // 销售排行榜
    def productCharts ={
        def hql = "select p.modelNo,sum(p.amount) from Product p where p.productFlag='卖出' group by p.modelNo"
        def resultList = Product.executeQuery(hql)
        if (resultList.size()==0)
        {
            render(view:"productChartsError");
        }
        else{
            def dataList = []
            resultList.each { s->
                def bar = ['modelNo':s[0], 'amount':s[1]]
                dataList << bar
            }
            [productChartList: dataList]
        }
    }
    
     // 每月销售排行榜
    def monthProductCharts ={
    }

    def doMonthProductCharts = {
        def year = params.pickDate_year
        def month = params.pickDate_month
        def iYear = Integer.parseInt(year)
        def iMonth = Integer.parseInt(month)
        
        def startDate = DateUtils.getMonthStart(year,month)
        def iDay = DateUtils.getMonthOfDays(iYear,iMonth)

        def c = Calendar.getInstance()
        c.set(iYear,iMonth-1,iDay)
        def endDate = c.getTime()

        def hql = "select p.modelNo,sum(p.amount) from Product p where p.productFlag='卖出' and p.time >= ? and p.time <= ? group by p.modelNo"
        def resultList = Product.executeQuery(hql,[startDate,endDate])
        if (resultList.size()==0)
        {
            render(view:"productChartsError");
        }
        else{
            def dataList = []
            resultList.each { s->
                def bar = ['modelNo':s[0], 'amount':s[1]]
                dataList << bar
            }
            render(view:"monthProductCharts",model:[productChartList: dataList])
        }
    }

}
